package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.ISysRoleService;
import com.yt.sys.models.service.ISysUserRoleService;
import com.yt.sys.models.service.ISysRolePermissionService;
import com.yt.sys.models.bo.SysRoleBO;
import com.yt.sys.models.bo.SysRoleSaveBO;
import com.yt.sys.models.dto.SysRoleDTO;
import com.yt.sys.models.vo.SysRoleVO;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色信息控制器
 *
 * @author yzz
 * @Date 2025-09-03 14:09:38
 */

@RestController
@RequestMapping("/api/sysRole")
@Slf4j
@Api(value = "SysRoleApiController",tags = "角色信息Api接口")
public class SysRoleApiController {

    @DubboReference
    private ISysRoleService sysRoleService;

    @DubboReference
    private ISysUserRoleService sysUserRoleService;

    @DubboReference
    private ISysRolePermissionService sysRolePermissionService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<SysRoleDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        SysRoleDTO dto = sysRoleService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "角色信息列表",notes = "角色信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<SysRoleDTO>> queryPageList(SysRoleBO bo){
        Wrapper<SysRoleDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<SysRoleDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = sysRoleService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    @ApiOperation(value = "获取所有角色信息", notes = "获取所有角色信息")
    @PostMapping("/listAll")
    public Result<List<SysRoleVO>> listAll() {
        List<SysRoleDTO> sysRoleList = sysRoleService.selectList(new EntityWrapper<>());
        List<SysRoleVO> sysRoleVOList = sysRoleList.stream().map(sysRoleDTO -> {
            SysRoleVO sysRoleVO = new SysRoleVO();
            sysRoleVO.setId(sysRoleDTO.getId());
            sysRoleVO.setRevision(sysRoleDTO.getRevision());
            sysRoleVO.setRoleName(sysRoleDTO.getRoleName());
            sysRoleVO.setRoleLogo(sysRoleDTO.getRoleLogo());
            sysRoleVO.setRoleDes(sysRoleDTO.getRoleDes());
            sysRoleVO.setStatus(sysRoleDTO.getStatus());
            sysRoleVO.setCreateTime(sysRoleDTO.getCreateTime());
            sysRoleVO.setUpdateTime(sysRoleDTO.getUpdateTime());
            return sysRoleVO;
        }).collect(Collectors.toList());
        return new Result<>(sysRoleVOList);
    }
    
    @ApiOperation(value = "更新角色状态", notes = "更新角色状态")
    @PostMapping("/updateStatus")
    public Result<Boolean> updateStatus(@RequestBody @ApiParam(value = "角色状态信息", required = true) SysRoleSaveBO saveBO) {
        // 参数校验
        if (saveBO.getId() == null || saveBO.getStatus() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        // 检查角色是否存在
        SysRoleDTO sysRoleDTO = sysRoleService.selectById(saveBO.getId());
        if (sysRoleDTO == null) {
            return new Result<>(CodeEnum.FAIL_100005);
        }
        
        // 更新状态
        sysRoleDTO.setStatus(saveBO.getStatus());
        boolean result = sysRoleService.updateById(sysRoleDTO);
        
        return new Result<>(result);
    }
    
    @ApiOperation(value = "添加角色", notes = "添加角色")
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody @ApiParam(value = "角色信息", required = true) SysRoleSaveBO saveBO) {
        // 参数校验
        if (saveBO == null || saveBO.getRoleName() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        // 设置创建时间和更新时间
        Date now = new Date();
        saveBO.setCreateTime(now);
        saveBO.setUpdateTime(now);
        
        // 调用服务添加角色
        boolean result = sysRoleService.add(saveBO);
        
        return new Result<>(result);
    }
    
    @ApiOperation(value = "编辑角色", notes = "编辑角色")
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody @ApiParam(value = "角色信息", required = true) SysRoleSaveBO saveBO) {
        // 参数校验
        if (saveBO == null || saveBO.getId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        // 检查角色是否存在
        SysRoleDTO sysRoleDTO = sysRoleService.selectById(saveBO.getId());
        if (sysRoleDTO == null) {
            return new Result<>(CodeEnum.FAIL_100005);
        }
        
        // 调用服务更新角色
        boolean result = sysRoleService.updateById(convertSaveBOToDTO(saveBO));
        
        return new Result<>(result);
    }
    
    @ApiOperation(value = "删除角色", notes = "删除角色")
    @PostMapping("/delete")
    public Result<Boolean> delete(@RequestBody @ApiParam(value = "角色ID信息", required = true) SysRoleSaveBO saveBO) {
        // 参数校验
        if (saveBO.getId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        // 检查角色是否存在
        SysRoleDTO sysRoleDTO = sysRoleService.selectById(saveBO.getId());
        if (sysRoleDTO == null) {
            return new Result<>(CodeEnum.FAIL_100005);
        }
        
        // 先删除与该角色关联的用户角色关联记录
        Wrapper userRoleWrapper = new EntityWrapper<>();
        userRoleWrapper.eq("role_id", saveBO.getId());
        sysUserRoleService.delete(userRoleWrapper);
        
        // 再删除与该角色关联的角色权限关联记录
        Wrapper rolePermissionWrapper = new EntityWrapper<>();
        rolePermissionWrapper.eq("role_id", saveBO.getId());
        sysRolePermissionService.delete(rolePermissionWrapper);
        
        // 调用服务删除角色
        boolean result = sysRoleService.deleteById(saveBO.getId());
        
        return new Result<>(result);
    }
    
    @ApiOperation(value = "搜索角色", notes = "根据角色名称搜索角色")
    @PostMapping("/search")
    public Result<List<SysRoleVO>> search(@RequestBody @ApiParam(value = "搜索条件") SysRoleSaveBO searchBO) {
        Wrapper<SysRoleDTO> wrapper = new EntityWrapper<>();
        
        // 如果提供了角色名称，进行模糊搜索
        if (searchBO.getRoleName() != null && !searchBO.getRoleName().trim().isEmpty()) {
            wrapper.like("role_name", searchBO.getRoleName());
        }
        
        // 查询匹配的角色
        List<SysRoleDTO> sysRoleList = sysRoleService.selectList(wrapper);
        
        // 转换为VO对象
        List<SysRoleVO> sysRoleVOList = sysRoleList.stream().map(sysRoleDTO -> {
            SysRoleVO sysRoleVO = new SysRoleVO();
            sysRoleVO.setId(sysRoleDTO.getId());
            sysRoleVO.setRevision(sysRoleDTO.getRevision());
            sysRoleVO.setRoleName(sysRoleDTO.getRoleName());
            sysRoleVO.setRoleLogo(sysRoleDTO.getRoleLogo());
            sysRoleVO.setRoleDes(sysRoleDTO.getRoleDes());
            sysRoleVO.setStatus(sysRoleDTO.getStatus());
            sysRoleVO.setCreateTime(sysRoleDTO.getCreateTime());
            sysRoleVO.setUpdateTime(sysRoleDTO.getUpdateTime());
            return sysRoleVO;
        }).collect(Collectors.toList());
        
        return new Result<>(sysRoleVOList);
    }
    
    /**
     * 将SysRoleSaveBO转换为SysRoleDTO
     * @param saveBO
     * @return
     */
    private SysRoleDTO convertSaveBOToDTO(SysRoleSaveBO saveBO) {
        SysRoleDTO dto = new SysRoleDTO();
        dto.setId(saveBO.getId());
        dto.setRevision(saveBO.getRevision());
        dto.setRoleName(saveBO.getRoleName());
        dto.setRoleLogo(saveBO.getRoleLogo());
        dto.setRoleDes(saveBO.getRoleDes());
        dto.setStatus(saveBO.getStatus());
        return dto;
    }
}